package com.sunny.l47;

import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;

public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        return bfs(root);
    }
    public ArrayList<ArrayList<Integer>> bfs(TreeNode root){
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if(null == root)
            return res;
        LinkedBlockingQueue<TreeNode> queue1 = new LinkedBlockingQueue<>();
        LinkedBlockingQueue<TreeNode> queue2 = new LinkedBlockingQueue<>();
        int size1 = 1;
        int size2 = 0;
        int tag = 1;
        queue1.offer(root);
        ArrayList<Integer> tmpRes = new ArrayList<>();
        while ((1 == tag && !queue1.isEmpty()) || (2 == tag && !queue2.isEmpty())){
            if(1 == tag){
                TreeNode tmp = queue1.poll();
                tmpRes.add(tmp.val);
                size1--;
                if(null != tmp.left){
                    queue2.offer(tmp.left);
                    size2++;
                }
                if(null != tmp.right){
                    queue2.offer(tmp.right);
                    size2++;
                }
                if(0 == size1){
                    tag = 2;
                    res.add(tmpRes);
                    tmpRes = new ArrayList<>();
                }
            }else if(2 == tag){
                TreeNode tmp = queue2.poll();
                tmpRes.add(tmp.val);
                size2--;
                if(null != tmp.left){
                    queue1.offer(tmp.left);
                    size1++;
                }
                if(null != tmp.right){
                    queue1.offer(tmp.right);
                    size1++;
                }
                if(0 == size2){
                    tag = 1;
                    res.add(tmpRes);
                    tmpRes = new ArrayList<>();
                }
            }
        }
        return res;
    }
}
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

